package cn.rengy.tool.core.util;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;

public class LotteryUtils {
	/**
	 * 实时抽奖
	 * @param orignalRates 原始的概率列表，保证顺序和实际物品对应
	 * @return 奖品的索引
	 */
	public static int lottery(List<Double> orignalRates) {
		if (orignalRates == null || orignalRates.isEmpty()) {
			return -1;
		}

		int size = orignalRates.size();

		// 计算总概率，这样可以保证不一定总概率是1
		double sumRate = 0d;
		for (double rate : orignalRates) {
			sumRate += rate;
		}
		if(sumRate==0){
			throw new RuntimeException("rate不能为0");
		}
		// 计算每个物品在总概率的基础下的概率情况
		List<Double> sortOrignalRates = new ArrayList<Double>(size);
		Double tempSumRate = 0d;
		for (double rate : orignalRates) {
			tempSumRate += rate;
			sortOrignalRates.add(tempSumRate / sumRate);
		}

		// 根据区块值来获取抽取到的物品索引
		double nextDouble = Math.random();
		sortOrignalRates.add(nextDouble);
		Collections.sort(sortOrignalRates);

		return sortOrignalRates.indexOf(nextDouble);
	}
	/**
	 * 后抽奖、随机抽奖
	 * @param num
	 * @return
	 */
	public static int randomInt(int num){
		Random r=new Random(); 
		return r.nextInt(num+1);
	}
	/**
	 * 两个金额之间随机数
	 * @param amount_min
	 * @param amount_max
	 * @return
	 */
	public static Double randomAmount(Double amount_min,Double amount_max){
		int redpacket_amount_min_int=((Double)(amount_min*100)).intValue();
		int redpacket_amount_max_int=((Double)(amount_max*100)).intValue();
		int d=redpacket_amount_max_int-redpacket_amount_min_int;
		int amount=new Random().nextInt(d+1)+redpacket_amount_min_int;
		return new Double(amount)/100;
	}
}